import Link from "next/link";
import { webAPI } from "@/lib/api";
import type { Article, Category } from "@/lib/api";
import ResponsiveLayout from "@/components/ResponsiveLayout";
import Footer from "@/components/Footer";
import DiscoverTabs from "@/components/DiscoverTabs";
import type { Metadata } from "next";
import RecommendedArticles from "@/components/RecommendedArticles";
import ContactUs from "@/components/ContactUs";
import Banner from "@/components/Banner";
import WeChatShareProvider from "@/components/WeChatShareProvider";

// 生成发现页面元数据
export async function generateMetadata({
  searchParams,
}: {
  searchParams?: Promise<{
    category?: string;
    page?: string;
  }>;
}): Promise<Metadata> {
  const resolvedSearchParams = await searchParams;
  const categoryId = resolvedSearchParams?.category ? Number(resolvedSearchParams.category) : undefined;

  // 获取分类信息用于SEO
  let categoryName = "";
  if (categoryId) {
    try {
      const catRes = await webAPI.getCategories();
      if (catRes.success) {
        const category = catRes.data.find((cat: Category) => cat.id === categoryId);
        categoryName = category?.name || "";
      }
    } catch (error) {
      console.error("获取分类信息失败:", error);
    }
  }

  const title = "发现 - 做好AI产品，打造下一款神级应用";

  const description = categoryName ? `探索${categoryName}相关的最新AI技术文章，了解人工智能在${categoryName}领域的最新应用和发展趋势。` : "探索最新的人工智能技术、工具和应用，发现AI带来的无限可能。汇集AI产品评测、技术解析、行业动态等优质内容。";

  return {
    title,
    description,
    keywords: ["AI文章", "人工智能", "AI技术", "AI应用", "AI工具", "机器学习", "深度学习", "自然语言处理", "计算机视觉", categoryName].filter(Boolean),
    openGraph: {
      title,
      description,
      type: "website",
      locale: "zh_CN",
      url: categoryId ? `/discover?category=${categoryId}` : "/discover",
      siteName: "AI产品之家",
      images: [
        {
          url: "/og-image.jpg",
          width: 1200,
          height: 630,
          alt: "AI产品之家 - 发现",
        },
      ],
    },
    twitter: {
      card: "summary_large_image",
      title,
      description,
      images: ["/og-image.jpg"],
    },
    alternates: {
      canonical: categoryId ? `/discover?category=${categoryId}` : "/discover",
    },
  };
}

export default async function Discover({
  searchParams,
}: {
  searchParams?: Promise<{
    category?: string;
    page?: string;
  }>;
}) {
  const resolvedSearchParams = await searchParams;
  const categoryId = resolvedSearchParams?.category ? Number(resolvedSearchParams.category) : undefined;

  // Fetch initial data on the server
  const catRes = await webAPI.getCategories();
  const categories: Category[] = catRes.success ? catRes.data : [];
  const artRes = await webAPI.getArticles({ page: 1, limit: 10, categoryId, status: true, sort: "createdAt:desc" });
  const initialArticles: Article[] = artRes.success ? artRes.data.articles : [];
  const initialTotalPages = artRes.success ? artRes.data.totalPages : 1;

  // 获取分类名称用于微信分享
  const categoryName = categoryId ? categories.find(cat => cat.id === categoryId)?.name || "" : "";

  // 生成结构化数据
  const structuredData = {
    "@context": "https://schema.org",
    "@type": "CollectionPage",
    name: categoryId ? `${categoryName}相关文章` : "AI文章发现",
    description: categoryId ? `探索${categoryName}相关的最新AI技术文章` : "探索最新的人工智能技术、工具和应用，发现AI带来的无限可能",
    url: categoryId ? `${process.env.NEXT_PUBLIC_SITE_URL || "https://aiproducthome.com"}/discover?category=${categoryId}` : `${process.env.NEXT_PUBLIC_SITE_URL || "https://aiproducthome.com"}/discover`,
    mainEntity: {
      "@type": "ItemList",
      itemListElement: initialArticles.map((article, index) => ({
        "@type": "ListItem",
        position: index + 1,
        item: {
          "@type": "Article",
          headline: article.title,
          description: article.summary || article.content.replace(/<[^>]*>/g, "").substring(0, 160),
          author: {
            "@type": "Person",
            name: article.author,
          },
          datePublished: article.publishedAt || article.createdAt,
          dateModified: article.updatedAt || article.publishedAt || article.createdAt,
          publisher: {
            "@type": "Organization",
            name: "AI产品之家",
            url: process.env.NEXT_PUBLIC_SITE_URL || "https://aiproducthome.com",
          },
          url: `${process.env.NEXT_PUBLIC_SITE_URL || "https://aiproducthome.com"}/discover/detail/${article.slug}`,
          image: article.coverImage
            ? {
                "@type": "ImageObject",
                url: article.coverImage,
                width: 800,
                height: 600,
              }
            : undefined,
        },
      })),
    },
    breadcrumb: {
      "@type": "BreadcrumbList",
      itemListElement: [
        {
          "@type": "ListItem",
          position: 1,
          name: "首页",
          item: `${process.env.NEXT_PUBLIC_SITE_URL || "https://aiproducthome.com"}`,
        },
        {
          "@type": "ListItem",
          position: 2,
          name: "发现",
          item: `${process.env.NEXT_PUBLIC_SITE_URL || "https://aiproducthome.com"}/discover`,
        },
        ...(categoryId
          ? [
              {
                "@type": "ListItem",
                position: 3,
                name: categoryName,
                item: `${process.env.NEXT_PUBLIC_SITE_URL || "https://aiproducthome.com"}/discover?category=${categoryId}`,
              },
            ]
          : []),
      ],
    },
  };

  return (
    <ResponsiveLayout active="discover">
      {/* 结构化数据 */}
      <script
        type='application/ld+json'
        dangerouslySetInnerHTML={{
          __html: JSON.stringify(structuredData),
        }}
      />

      <WeChatShareProvider 
        title={categoryId ? `${categoryName}相关文章 - AI产品之家` : "AI产品之家-发现：做好AI产品，打造下一款神级应用"}
        description={categoryId ? `探索${categoryName}相关的最新AI技术文章，了解人工智能在${categoryName}领域的最新应用和发展趋势。` : "洞悉发展趋势、激发创意灵感、掌握增长密码、探索商业路径。"}
        imageUrl="/banner/discover_banner_pc.png"
      />

      {/* Banner */}
      <Banner pcImage='/banner/discover_banner_pc.png' mobileImage='/banner/discover_banner_mb.png' alt='发现AI世界 - 探索最新的人工智能技术、工具和应用' />

      {/* Category Filters */}
      <nav className='container mx-auto max-w-6xl px-4 py-4' aria-label='文章分类导航'>
        <div className='space-y-2 flex'>
          {/* <span className="text-base font-bold text-gray-700 w-[50px] pr-2 pt-2">分类:</span> */}
          <div className='flex flex-wrap items-center gap-2'>
            <Link href='/discover' className={`px-4 py-2 text-sm rounded-full border transition-all duration-200 ease-in-out transform hover:-translate-y-0.5 ${!categoryId ? "bg-blue-600 text-white border-blue-600 font-semibold shadow-sm" : "bg-white text-gray-700 border-gray-300 hover:bg-gray-100 hover:border-gray-400 font-medium"}`} aria-current={!categoryId ? "page" : undefined}>
              全部
            </Link>
            {categories.map(cat => (
              <Link key={cat.id} href={`/discover?category=${cat.id}`} className={`px-4 py-2 text-sm rounded-full border transition-all duration-200 ease-in-out transform hover:-translate-y-0.5 ${categoryId === cat.id ? "bg-blue-600 text-white border-blue-600 font-semibold" : "bg-white text-gray-700 border-gray-300 hover:bg-gray-100 hover:border-gray-400 font-medium"}`} aria-current={categoryId === cat.id ? "page" : undefined}>
                {cat.name}
              </Link>
            ))}
          </div>
        </div>
      </nav>

      {/* Main Content */}
      <div className='container mx-auto max-w-6xl px-4 pb-8'>
        <div className='grid grid-cols-1 lg:grid-cols-3 gap-8'>
          <div className='lg:col-span-2'>
            <DiscoverTabs initialArticles={initialArticles} initialTotalPages={initialTotalPages} categoryId={categoryId} />
          </div>

          {/* Right Sidebar */}
          <aside className='lg:col-span-1 space-y-8'>
            <div className='bg-white rounded-xl border border-gray-200 shadow-sm p-6'>
              <h2 className='font-bold text-lg mb-4 border-b border-gray-200 pb-3 text-gray-800'>推荐文章</h2>
              <RecommendedArticles />
            </div>
            <ContactUs />
          </aside>
        </div>
      </div>
      <Footer />
    </ResponsiveLayout>
  );
}
